package com.happy_hao.topbiz.util;

import cn.hutool.json.JSONUtil;
import com.happy_hao.topbiz.exception.ServiceException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public boolean set(String key, Object value) {
        try{
            redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value));
            return true;
        } catch (Exception e) {
            log.error("redis set error:key:{},value:{},e:",key,value,e);
            throw new ServiceException("redis set error");
        }
    }

    public  boolean set(String key, Object value, Long expireTime) {
        try{
            redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), expireTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("redis set error:key:{},value:{},expireTime,{},e:",key,value,expireTime,e);
            throw new ServiceException("redis set error");
        }
    }

    public Object get(String key) {
        try{
            return StringUtils.hasText(key)?redisTemplate.opsForValue().get(key):null;
        } catch (Exception e) {
            log.error("redis get error:key:{},e:",key,e);
            return null;
        }
    }

    public boolean delete(String... keys) {
        if (keys == null || keys.length == 0) return false;
        try {
            if (keys.length == 1) {
                redisTemplate.delete(keys[0]);
            } else {
                redisTemplate.delete(Arrays.asList(keys)); // 安全转换
            }
            return true;
        } catch (Exception e) {
            log.error("Redis delete error for keys: {}", Arrays.toString(keys), e);
            throw new ServiceException("Redis delete error");
        }
    }

    public boolean keyExist(String key){
        try{
            return StringUtils.hasText(key)?redisTemplate.hasKey(key):false;
        } catch (Exception e) {
            log.error("redis keyExist error:key:{},e:",key,e);//e不需要占位符
            throw new ServiceException("redis keyExist error");
        }
    }
}
